<template>
  <div :class="isAllFullScreen ? 'video-feed  videoall' : 'video-feed'" @touchstart="handleTouchStart"
    @touchmove="handleTouchMove" @touchend="handleTouchEnd" @wheel="handleWheel">
    <div v-if="isAllFullScreen" @click="handleBack"
      style="position: absolute;top: 35px;left: 50px;z-index: 20;cursor: pointer">
      <div style="background-color: rgba(0,0,0,0.5)
;padding: 3px;border-radius: 50%">
        <ChevronLeftIcon style="color: white;font-size: 30px" />
      </div>

    </div>

    <div  class="video-container" ref="scrollContainer">
      <div v-if="!listLoading && !videoList.length" style="display: flex;justify-content: center;align-items: center;
height: 100%;position: relative;overflow: hidden;">
        <Vortex
            background-color="black"
            :range-y="800"
            :particle-count="500"
            :base-hue="120"
            class="flex size-full flex-col items-center justify-center px-2 py-4"
            style="width: 100%;height: 100%;position: absolute;top: 0;left: 0;right: 0;bottom: 0;"
        >

        </Vortex>
        <BlurReveal :duration="0.5"  :delay="0.2">
          <span style="font-size: 45px">嗨👋</span>
          <span style="font-size: 35px">你全都看完啦！</span>
        </BlurReveal>

      </div>
      <div   v-if="listLoading" style="overflow: hidden !important;width: 100%;position: relative;
height: 100%;">
        <t-skeleton
            style="flex: 20"
            animation="gradient"
            :row-col="[
              [{ type: 'rect', width: '100%', height: '100vh', marginLeft: '0%' },]]"   />
      </div>
      <div v-show="!listLoading" v-for="(item, index) in videoList" :key="index" class="video-block">
        <div class="videoLeft">
          <div class="video-content">
            <video @click="handleClickVideo" ref="videoRef" class="video"
                   style="object-fit: contain;width: 100%;height: 100%;"
                   :src="item.isActive || item.isNext ? item.videoUrl : ''"
                   :preload="item.isNext ? 'metadata' : 'auto'"
                   loop></video>
          </div>
          <div class="videoControl">
            <div class="progress-bar" ref="progressBarRef" @mousedown="startProgressDrag"
                 @touchstart.passive="startProgressDrag">
              <div class="progress" :style="{ width: progress + '%' }"></div>
            </div>
            <div class="control-bar">
              <div class="video-detail">
                <h2 style="margin-bottom: 10px;font-size: 18px;font-weight: bolder;">@{{ item.authorName }}</h2>
                <p style="font-size: 14px; margin: 0">{{ item.videoTitle }}</p>
              </div>
              <div class="left-controls">
                <button class="play-pause" @click.stop="togglePlay">
                  <span v-if="isPlaying">❚❚</span>
                  <span v-else>▶</span>
                </button>
                <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
              </div>
              <div class="right-controls">
                <div class="volume-control" @mouseenter="showVolumeSlider = true"
                     @mouseleave="showVolumeSlider = false">
                  <button class="volume-button">
                    <span v-if="volume > 0.5">🔊</span>
                    <span v-else-if="volume > 0">🔉</span>
                    <span v-else>🔇</span>
                  </button>
                  <div class="volume-slider" v-show="showVolumeSlider">
                    <input type="range" min="0" max="1" step="0.01" v-model="volume" @input="setVolume">
                  </div>
                </div>
                <button class="fullscreen-button" @click.stop="toggleFullscreen">
                  <span>⛶</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="videoDialog" :style="{
          width: videoDialogShow ? '370px' : '0px',
          padding: videoDialogShow ? '15px' : '0px'
        }">
          <div class="videoOperate">
            <div class="operate">
              <div class="buttons">
                <span class="iconContainer" style="margin-bottom: 30px">
                  <div style="position: relative">
                                      <t-avatar @click="handleAvatar(item)"
                                           style="cursor: pointer; width: 50px;height: 50px; border-radius: 50%; overflow: hidden"
                                                :src="item.authorAvatar" alt=""></t-avatar>
                    <div style="position: absolute;top: 40px;right: 18px;
                    background-color: white;border-radius: 22px;
                    display: flex; justify-content: center; align-items: center;
                      "
                    v-if="!item.isGuanZhu"
                    @click="handleOperate(item , 4 , 1)"
                    >
                      <AddCircleFilledIcon style="color: red;font-size: 17px;cursor: pointer" /></div>
                  </div>

                </span>
                <span class="iconContainer">

                  <svg @click="handleOperate(item , 1 , 1)" v-if="!item.isLiked" t="1743310920891" class="icon" viewBox="0 0 1024 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="4598" width="200" height="200">
                    <path
                        d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z"
                        fill="#ffffff" p-id="4599"></path>
                  </svg>
                  <svg @click="handleOperate(item , 1)" v-else t="1743310920891" class="icon" viewBox="0 0 1024 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="4598" width="200" height="200">
                    <path
                        d="M667.786667 117.333333C832.864 117.333333 938.666667 249.706667 938.666667 427.861333c0 138.250667-125.098667 290.506667-371.573334 461.589334a96.768 96.768 0 0 1-110.186666 0C210.432 718.368 85.333333 566.112 85.333333 427.861333 85.333333 249.706667 191.136 117.333333 356.213333 117.333333c59.616 0 100.053333 20.832 155.786667 68.096C567.744 138.176 608.170667 117.333333 667.786667 117.333333z"
                        fill="#d81e06" p-id="4599"></path>
                  </svg>
                  <span>{{ item.likeNumber }}</span>
                </span>
                <span @click="videoDialogShow = true" class="iconContainer">
                  <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="200"
                       height="200">
                    <path
                        d="M507.904 60.416q93.184-1.024 175.104 33.792t143.872 94.72 97.792 141.312 36.864 174.592q1.024 88.064-30.208 165.888t-87.04 137.728-131.072 98.816-162.304 48.128q-22.528 3.072-48.128 5.12t-56.832 3.072-69.632 0-86.528-6.144q-106.496-10.24-158.208-26.624t-41.472-18.432q54.272-9.216 93.184-29.696 20.48-11.264 16.896-32.256t-19.968-39.424q-52.224-57.344-84.48-133.632t-34.304-164.352q-1.024-93.184 33.792-175.104t95.232-143.36 142.336-97.28 175.104-36.864zM707.584 510.976q0 26.624 18.432 45.568t45.056 18.944 45.568-18.944 18.944-45.568-18.944-45.056-45.568-18.432-45.056 18.432-18.432 45.056zM450.56 510.976q0 26.624 19.456 46.08t46.08 19.456q27.648 0 46.592-19.456t18.944-46.08q0-27.648-18.944-46.592t-46.592-18.944q-26.624 0-46.08 18.944t-19.456 46.592zM196.608 509.952q0 26.624 18.944 46.08t45.568 19.456q27.648 0 46.592-19.456t18.944-46.08-18.944-45.568-46.592-18.944q-26.624 0-45.568 18.944t-18.944 45.568z"
                        fill="#ffffff"></path>
                  </svg>
                  <span>{{ item.reviewNumber }}</span>
                </span>
                <span class="iconContainer" style="margin-bottom: 40px">
                  <svg @click="handleOperate(item , 2 , 1)" v-if="!item.isShouCang" t="1743311017436" class="icon" viewBox="0 0 1092 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="5704" width="200" height="200">
                    <path
                        d="M1080.270639 453.733718c-77.161903 88.184889-214.58473 234.425705-214.58473 234.425705s22.045972 160.203798 35.273956 269.70066c5.878993 55.85193-37.478953 80.101899-85.980892 58.054927-92.594883-43.357945-233.690706-110.96686-265.290665-126.399841-32.334959 14.697981-174.165781 81.571897-267.495663 124.928843-49.236938 21.310973-92.594883-2.204997-87.45089-58.054927 12.492984-109.496862 35.273956-268.965661 35.273955-268.965661S91.123885 541.917607 13.227983 453.732718c-27.924965-32.334959-9.551988-77.896902 44.827944-85.980891 111.701859-19.841975 284.397642-51.441935 284.397642-51.441935s94.798881-163.143794 154.324805-263.086669C529.848333-7.7717 552.629304-0.422709 556.304299 1.047289c10.287987 2.939996 26.455967 15.431981 47.032941 52.175934 58.789926 99.943874 152.119808 263.087669 152.119808 263.087669s170.491785 31.60096 280.723647 51.441935c53.645932 8.08399 71.28291 54.380931 44.092944 85.980891z"
                        fill="#ffffff" p-id="5705"></path>
                  </svg>
                  <svg @click="handleOperate(item , 2)" t="1743311017436" v-else class="icon" viewBox="0 0 1092 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="5704" width="200" height="200">
                    <path
                        d="M1080.270639 453.733718c-77.161903 88.184889-214.58473 234.425705-214.58473 234.425705s22.045972 160.203798 35.273956 269.70066c5.878993 55.85193-37.478953 80.101899-85.980892 58.054927-92.594883-43.357945-233.690706-110.96686-265.290665-126.399841-32.334959 14.697981-174.165781 81.571897-267.495663 124.928843-49.236938 21.310973-92.594883-2.204997-87.45089-58.054927 12.492984-109.496862 35.273956-268.965661 35.273955-268.965661S91.123885 541.917607 13.227983 453.732718c-27.924965-32.334959-9.551988-77.896902 44.827944-85.980891 111.701859-19.841975 284.397642-51.441935 284.397642-51.441935s94.798881-163.143794 154.324805-263.086669C529.848333-7.7717 552.629304-0.422709 556.304299 1.047289c10.287987 2.939996 26.455967 15.431981 47.032941 52.175934 58.789926 99.943874 152.119808 263.087669 152.119808 263.087669s170.491785 31.60096 280.723647 51.441935c53.645932 8.08399 71.28291 54.380931 44.092944 85.980891z"
                        fill="#f4ea2a" p-id="5705"></path>
                  </svg>
                  <span>{{ item.shouCangNumber }}</span>
                </span>
                <span class="iconContainer">
                  <svg class="icon" viewBox="0 0 1192 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="200"
                       height="200">
                    <path
                        d="M785.974088 937.204113l373.988158-381.008413a114.238704 114.238704 0 0 0 0-159.551262L785.974088 14.997819A49.460891 49.460891 0 0 0 702.369227 49.779994v186.674976c-287.192272 0-641.715176 122.216267-702.025554 681.602992a35.101278 35.101278 0 0 0 63.820505 24.570894c191.461514-269.641633 603.103771-236.45497 638.205049-236.45497v196.567155a49.460891 49.460891 0 0 0 83.604861 34.463072zM702.369227 1024"
                        fill="#ffffff"></path>
                  </svg>
                  <span>{{ item.fenXiangNumber }}</span>
                </span>
              </div>
            </div>
          </div>
          <div v-if="!videoDialogShow" @click="handleAvatar(item)" class="btn2">
            <ChevronLeftIcon class="btn2-1" size="20px" />
          </div>
          <VideoDialog @handleOperate="handleOperate" v-if="item.isActive" :video="item" :video-id="item.videoId" @handleChangeVideo="handleChangeVideo"
                       @handleVisablechange="videoDialogShow = false"
                       :user-id="item.authorId"
                       :is-all-full-screen="isAllFullScreen"
          >

          </VideoDialog>
        </div>
      </div>
    </div>
    <div v-if="!isAllFullScreen" class="videoRight">
      <div
        style="background-color: rgba(69,69,69,0.8); width: 30px; height: 70px; border-radius: 20px; display: flex; flex-direction: column; align-items: center; justify-content: space-around">
        <svg @click="handlePreVideo" class="icon1" viewBox="0 0 1024 1024" version="1.1"
          xmlns="http://www.w3.org/2000/svg" width="200" height="200">
          <path
            d="M480.1 291.4c-0.8 0.6-1.7 1.4-2.5 2.1L82.7 654c-21.5 19.6-23 52.9-3.4 74.4 19.6 21.5 52.9 23 74.4 3.4l359.8-328.3 358.8 328.6c21.4 19.6 54.7 18.2 74.4-3.3 19.6-21.4 18.2-54.7-3.3-74.4L549.1 293.3c-19.6-18-49.1-18.3-69-1.9z"
            fill="#cdcdcd"></path>
        </svg>
        <svg @click="handleNextVideo" style="transform: rotateX(180deg);" class="icon1" viewBox="0 0 1024 1024"
          version="1.1" xmlns="http://www.w3.org/2000/svg" width="200" height="200">
          <path
            d="M480.1 291.4c-0.8 0.6-1.7 1.4-2.5 2.1L82.7 654c-21.5 19.6-23 52.9-3.4 74.4 19.6 21.5 52.9 23 74.4 3.4l359.8-328.3 358.8 328.6c21.4 19.6 54.7 18.2 74.4-3.3 19.6-21.4 18.2-54.7-3.3-74.4L549.1 293.3c-19.6-18-49.1-18.3-69-1.9z"
            fill="#cdcdcd"></path>
        </svg>
      </div>
    </div>
  </div>
</template>

<script setup lang="jsx" >
import {useVideoStore} from "@/stores/modules/video";
import {useRoute , useRouter} from "vue-router";
const route = useRoute()
const router = useRouter()

const queryFrom = {
  pageSize: 5,
  pageNumber: 1,
  userId: route.query.userId
}
const type = route.query.type ? route.query.type : 0;
const videoStore = useVideoStore()
import {
  reqAddUserLikeVideo,
  reqAddUserViewVideo,
  reqNotOperateVideo,
  reqOperateVideo,
  reqReviewList,
  reqUserVideoList,
  reqVideoList
} from '@/api/video/index'
import { ChevronLeftIcon, CloseIcon , AddCircleFilledIcon} from 'tdesign-icons-vue-next';
import Input from "@/components/Input.vue";
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import VideoDialog from "@/components/VideoDialog.vue";
import {MessagePlugin} from "tdesign-vue-next";

const listLoading = ref(true)

// 点击用户头像时
const handleAvatar = (item) => {
  videoDialogShow.value = true;
  getUserVideoList(item)
}

// 获取视频列表
import axios from 'axios';
import BlurReveal from "@/components/ui/BlurReveal.vue";


// 保存当前请求的 CancelToken 源
let currentCancelToken = null;



const handleOperate = async (item , type , operate) => {
  let title = ''
  switch (type) {
    case 1: title = '喜欢';break;
    case 2: title = '收藏';item.shouCangNumber++;break;
    case 3: title = '分享';item.fenXiangNumber++;break;
    case 4: title = '关注';break;
  }
  const obj = {
    videoId: item.videoId,
    type: type,
    userId: item.authorId
  }

  if (operate === 1) {
    const res = await reqOperateVideo(obj);
    if (res.code === 200) {
      switch (type) {
        case 1: item.isLiked = true;item.likeNumber++;break;
        case 2: item.isShouCang = true;item.shouCangNumber++;break;
        case 3: item.fenXiangNumber++;break;
        case 4: item.isGuanZhu = true;break;
      }
      reqAddUserLikeVideo(obj)
      MessagePlugin.success(`${title}成功！`)
    } else {
      MessagePlugin.error(`${title}失败！`)
    }
  } else {
    const res = await reqNotOperateVideo(obj);
    if (res.code === 200) {
      switch (type) {
        case 1: item.isLiked = false;item.likeNumber--;break;
        case 2: item.isShouCang = false;item.shouCangNumber--;break;
        case 3: item.fenXiangNumber--;break;
        case 4: item.isGuanZhu = false;break;
      }

      MessagePlugin.success(`取消${title}成功！`)
    } else {
      MessagePlugin.error(`取消${title}失败！`)
    }
  }


}

// 获取用户个人视频列表
const getUserVideoList = async (props) => {
  // 如果有正在进行的请求，则取消它
  if (currentCancelToken) {
    console.log('已有请求')
    currentCancelToken.cancel('已取消上一个请求');
  }
  // 创建新的 CancelToken 源
  currentCancelToken = axios.CancelToken.source();

  videoStore.isLoad = true;
  try {
    // 假设 reqUserVideoList 是基于 axios 的请求函数，
    // 并且它支持传入 cancelToken 选项
    const res = await reqUserVideoList({
      userId: props.authorId,
      type: '0',
      cancelToken: currentCancelToken.token
    });
    if (res.code === 200) {
      const dataList = res.data;
      dataList.forEach(item => item.isPlaying = item.videoId === props.videoId);
      videoStore.videoList = dataList;
      videoStore.authorInfo = dataList[0];
    } else {
      MessagePlugin.error("获取用户视频列表失败");
    }

    const res2 = await reqReviewList({videoId: props.videoId});
    if (res2.code === 200) {
      videoStore.reviewList = res2.data;
    }
  } catch (error) {
    // 判断是否是因为请求被取消
    if (axios.isCancel(error)) {
      console.log('请求取消:', error.message);
    } else {
      MessagePlugin.error("获取用户视频列表失败");
      console.error(error);
    }
  } finally {
    videoStore.isLoad = false;
  }
};


const isAllFullScreen = ref(false);

if (type != 0 && type != 2 && type != 3) {
  isAllFullScreen.value = true;
}

const videoDialogShow = ref(false)
const videoRef = ref([]);
const currentVideoRef = ref(null);
const progressBarRef = ref([]);
const currProgressBarRef = ref(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const progress = ref(0);
const volume = ref(0.7);
const showVolumeSlider = ref(false);
const isFullscreen = ref(false);
const isDraggingProgress = ref(false);
const videoList = ref([]);
const isFirstEnter = ref(true);
const scrollContainer = ref(null);
const videoModel = ref(false)
const confettiButton = ref(null)

let observer = null;

onUnmounted(() => {
  if (observer) observer.disconnect();
});

onMounted(() => {
  listLoading.value = true;
  getVideoList({ type: type, ...queryFrom });
});


//　点击退出全屏时
const handleBack = () => {
  if (route.query.redirect) {
    router.push(route.query.redirect);
    return
  }

  isAllFullScreen.value = false;
  videoList.value = videoStore.oldVideoList
  const videoId = videoStore.oldVideoList.filter(item => item.isActive)[0].videoId
  scrollTo(videoId);
}

// 发送
const inputEnter = () => {

}

// 当视频源变化时
const handleChangeVideo = async (id) => {
  isAllFullScreen.value = true
  if (!videoModel.value) {
    // 保存一份
    videoStore.oldVideoList = videoList.value
    // 清空旧视频列表
    videoList.value = []
    videoList.value = videoStore.videoList;
    await nextTick();
    setupObserver()
    videoModel.value = true
  }
  scrollTo(id)
}
// 滑动到指定id页
const scrollTo = (id) => {
  // 找到点击视频的位置，模拟滑动
  const index = videoList.value.findIndex(item => item.videoId === id); // 返回 1

  let count = 0;

  // 当前滚动位置
  const currentScroll = scrollContainer.value.scrollTop;

  // 容器可视高度
  const containerHeight = scrollContainer.value.clientHeight;

  // 计算下一个滚动位置（当前滚动位置 + 容器高度 + 步长）
  const nextScroll = containerHeight * index;

  // 最大可滚动高度（避免超出范围）
  const maxScroll = scrollContainer.value.scrollHeight - containerHeight;

  // 平滑滚动到目标位置
  scrollContainer.value.scrollTo({
    top: Math.min(nextScroll, maxScroll), // 不能超过最大滚动范围
    behavior: 'smooth' // 平滑滚动
  });
}

const debounce = (fn, delay) => {
  let timeout = null;
  return (...args) => {
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
};

// 上一个视频
const handlePreVideo = () => {
  if (!scrollContainer.value) return;
  scrollContainer.value.scrollBy({
    top: -window.innerHeight,
    behavior: 'smooth'
  });
};

// 下一个视频
const handleNextVideo = () => {
  if (!scrollContainer.value) return;
  scrollContainer.value.scrollBy({
    top: window.innerHeight,
    behavior: 'smooth'
  });
};

const getVideoList = async (obj) => {
  let isContinue = false
  const res = await reqVideoList(obj);
  if (res.code == 200) {
    if (res.data.length > 0) {
      res.data.forEach(item => {
        videoList.value.push(item);
      })
      isContinue = true
      listLoading.value = false
      queryFrom.pageNumber++
    } else {
      MessagePlugin.success({content : '已经到底啦！'})
      listLoading.value = false
      nextTick(() => {
        handleClickPiaoDai()
      })

    }
  } else {
    MessagePlugin.error({content :'获取视频列表失败！'})
    listLoading.value = false
  }

  await nextTick();
  if (isContinue) {
    setupObserver();
  }

};

const setupObserver = () => {
  if (observer) observer.disconnect();
  observer = new IntersectionObserver(
    debounce(async (entries) => {
      for (const entry of entries) {
        const index = videoRef.value.findIndex((item) => item === entry.target);
        if (index === -1) continue;

        if (entry.isIntersecting) {
          // 重置所有视频状态
          videoList.value.forEach((item, i) => {
            item.isActive = i === index;
            item.isNext = i === index + 1;
          });

          // 暂停其他视频并清理
          videoRef.value.forEach((videoEl, i) => {
            if (i !== index && videoEl && !videoEl.paused) {
              videoEl.pause();
              videoEl.currentTime = 0;
            }
          });

          currentVideoRef.value = videoRef.value[index];
          currProgressBarRef.value = progressBarRef.value[index];
          console.log("当前可见的视频索引:", index);

          videoStore.videoList.forEach((video) => {
            video.isPlaying = video.videoId === videoList.value[index].videoId;
          })
          if (isFirstEnter.value) {
            isFirstEnter.value = false;
          } else {
            setTimeout(() => {
              if (currentVideoRef.value && currentVideoRef.value.paused) {
                currentVideoRef.value.play().catch((err) => {
                  console.error("播放失败:", err);
                });
                isPlaying.value = true;
              }
            }, 100);
          }

          // 绑定事件
          currentVideoRef.value.addEventListener('timeupdate', updateProgress);
          currentVideoRef.value.addEventListener('loadedmetadata', () => {
            duration.value = currentVideoRef.value?.duration || 0;
          });
          currentVideoRef.value.addEventListener('ended', () => {
            isPlaying.value = false;
          });
          currentVideoRef.value.addEventListener('error', (e) => {
            console.error("视频加载错误:", e);
          });
          currentVideoRef.value.volume = volume.value;
          if (!isAllFullScreen.value) {
            videoDialogShow.value = false
          }

          // 如果开着展示框则获取用户详细数据
          if (videoDialogShow.value && !isAllFullScreen.value) {
            getUserVideoList(videoList.value[index])
          }

          await reqAddUserViewVideo({videoId : videoList.value[index].videoId})

          // 如果接近列表末尾，加载更多视频
          if (index == videoList.value.length - 1 && !isAllFullScreen.value) {
            console.log('扩容')
            getVideoList({type:type , ...queryFrom });
          }
        }
      }
    }, 200),
    { threshold: 0.7, rootMargin: "0px" }
  );

  videoRef.value.forEach((el) => {
    if (el) observer.observe(el);
  });
};

const handleClickVideo = () => {
  togglePlay();
};

const togglePlay = () => {
  if (!currentVideoRef.value) return;
  if (currentVideoRef.value.paused) {
    currentVideoRef.value.play().catch((err) => console.error("播放失败:", err));
    isPlaying.value = true;
  } else {
    currentVideoRef.value.pause();
    isPlaying.value = false;
  }
};

const updateProgress = () => {
  if (!currentVideoRef.value || isDraggingProgress.value) return;
  currentTime.value = currentVideoRef.value.currentTime;
  duration.value = currentVideoRef.value.duration;
  progress.value = (currentTime.value / duration.value) * 100;
};

const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const setVolume = () => {
  if (!currentVideoRef.value) return;
  currentVideoRef.value.volume = volume.value;
};

const toggleFullscreen = () => {
  if (!currentVideoRef.value) return;
  if (!document.fullscreenElement) {
    currentVideoRef.value.requestFullscreen().catch((err) => {
      console.error(`全屏失败: ${err.message}`);
    });
    isFullscreen.value = true;
  } else {
    document.exitFullscreen();
    isFullscreen.value = false;
  }
};

const startProgressDrag = (e) => {
  isDraggingProgress.value = true;
  handleProgressDrag(e);
  document.addEventListener('mousemove', handleProgressDrag);
  document.addEventListener('touchmove', handleProgressDrag);
  document.addEventListener('mouseup', stopProgressDrag);
  document.addEventListener('touchend', stopProgressDrag);
};

const handleProgressDrag = (e) => {
  if (!isDraggingProgress.value || !currProgressBarRef.value || !currentVideoRef.value) return;
  const rect = currProgressBarRef.value.getBoundingClientRect();
  let clientX = e instanceof MouseEvent ? e.clientX : e.touches[0].clientX;
  let percent = (clientX - rect.left) / rect.width;
  percent = Math.max(0, Math.min(1, percent));
  progress.value = percent * 100;
  currentVideoRef.value.currentTime = percent * duration.value;
  currentTime.value = currentVideoRef.value.currentTime;
};

const stopProgressDrag = () => {
  isDraggingProgress.value = false;
  document.removeEventListener('mousemove', handleProgressDrag);
  document.removeEventListener('touchmove', handleProgressDrag);
  document.removeEventListener('mouseup', stopProgressDrag);
  document.removeEventListener('touchend', stopProgressDrag);
};

const handleTouchStart = (e) => { };
const handleTouchMove = (e) => { };
const handleTouchEnd = (e) => { };
const handleWheel = (e) => { };


// ui动效
import confetti from "canvas-confetti";
import Vortex from "@/components/ui/Vortex.vue";

function handleClickPiaoDai() {
  const end = Date.now() + 3 * 1000; // 3 seconds
  const colors = ["#e10f35", "#fd8bbc", "#f3c20a", "#f8deb1"];

  // Frame function to trigger confetti cannons
  function frame() {
    if (Date.now() > end) return;

    // Left side confetti cannon
    confetti({
      particleCount: 2,
      angle: 60,
      spread: 55,
      startVelocity: 60,
      origin: { x: 0, y: 0.5 },
      colors: colors,
    });

    // Right side confetti cannon
    confetti({
      particleCount: 2,
      angle: 120,
      spread: 55,
      startVelocity: 60,
      origin: { x: 1, y: 0.5 },
      colors: colors,
    });

    requestAnimationFrame(frame); // Keep calling the frame function
  }

  frame();
}

</script>

<style scoped lang="less">
.videoall {
  position: absolute !important;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 99;
}

::v-deep(.t-list) {
  background: transparent !important;
}

::v-deep(.t-comment__avatar) {
  margin-right: 15px;
}

::v-deep(.t-list--split .t-list-item::after) {
  margin: 15px;
}

.chat-sender {
  flex: 10;
}

.t-iocn {
  cursor: pointer;
}

.reviewContainer {
  height: 100%;
}


::v-deep(.t-comment__avatar-image) {
  width: 40px;
  height: 40px;
}

.reviewList {
  /* 自定义滚动条轨道（背景） */
  scrollbar-color: #c1c1c1 transparent;
  /* Firefox */
  scrollbar-width: thin;
  /* Firefox */
  margin-top: 10px;
  overflow: auto;
  max-height: 55vh;
}



.dialogContent {
  color: rgb(235, 235, 235);
  box-sizing: border-box;
  padding: 10px 4px;
  min-width: 100%;
  height: 100% !important;
}

.videoDialogContainer {
  transition: 0.3s;
  min-width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.tabs .isActive {
  border-bottom: 3px solid red;
  color: white;
}

.tabs li {
  border-bottom: 3px solid transparent;
  margin-right: 20px;
  padding: 10px 3px;
  font-size: 14px;
  cursor: pointer;
  transition: 0.5s;
}

.videoDialogHeader {
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  color: #c0c0d6;
}


.btn2 {
  position: absolute;
  left: -30px;
  z-index: 1;
  background-color: black;
  top: 45%;
  cursor: pointer;
  padding: 10px 5px;
  border-bottom-left-radius: 50%;
  border-top-left-radius: 50%;
  border: 1px solid grey;
  border-right: none;
  transition: 0.3s;
}

.btn2:hover {
  color: white;
  border: 1px solid white;
  border-right: none;
}

.btn2 .btn2-1 {
  color: grey;
}

.btn2:hover .btn2-1 {
  color: white;
}

.videoLeft {
  flex: 20;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  background-color: black;
  align-items: center;
  position: relative;
  overflow: hidden;
  scroll-snap-align: start;
  flex-direction: column;
}

.videoDialog {
  width: 0px;
  height: 100%;
  position: relative;
  transition: 0.3s;
  background-color: rgb(12, 0, 0);
  box-sizing: border-box;
}

.video-block {
  flex: 20;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  background-color: black;
  border-radius: 20px;
  align-items: center;
  position: relative;
  overflow: hidden;
  scroll-snap-align: start;
}

.icon1 {
  width: 13px;
  height: 13px;
  cursor: pointer;
}

.iconContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.buttons {
  display: flex;
  flex-direction: column;
  color: white;
}

.icon {
  width: 30px;
  height: 30px;
  margin-bottom: 5px;
  cursor: pointer;
}

.operate {
  height: 60%;
  width: 100%;
  background-color: transparent;
}

.videoOperate {
  margin-top: 50px;
  height: 100%;
  position: absolute;
  width: 7.5%;
  background-color: transparent;
  left: -50px;
  display: flex;
  align-items: center;
}

.videoDetail {
  background-color: transparent;
  height: 100%;
  width: 30px;
  position: absolute;
  right: -10%;
}

.video-content {
  width: 100%;
  height: 92%;
  display: flex;
  position: relative;
  justify-content: center;
}

.video-detail {
  position: absolute;
  color: white;
  top: -300%;
  z-index: 99;
}

.video-feed {
  width: 100%;
  height: 100%;
  display: flex;
  color: #c0c0d6;
  position: relative;
}

.video-container {
  flex: 20;
  width: 100%;
  height: 100%;
  background-color: black;
  border-radius: 20px;
  position: relative;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  scroll-snap-type: y mandatory;
}

.video-container::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
}

.video {
  width: 85%;
  object-fit: cover;
  height: 100%;
}

.videoControl {
  width: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  justify-content: center;
}

.progress-bar {
  width: 100%;
  height: 4px;
  background-color: #555;
  cursor: pointer;
}

.progress {
  height: 100%;
  background-color: white;
  width: 0;
}

.control-bar {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  box-sizing: border-box;
  align-items: center;
  height: 30px;
  position: relative;
  margin-top: 5px;
}

.left-controls,
.right-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.play-pause {
  transform: translateY(-10%);
}

.play-pause,
.volume-button,
.fullscreen-button {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
}

.time-display {
  color: white;
  font-size: 14px;
}

.volume-control {
  position: relative;
}

.volume-slider {
  position: absolute;
  bottom: 30px;
  left: 50%;
  transform: translateX(-50%) translateY(-40%) rotate(-90deg);
  width: 80px;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px 5px;
  border-radius: 5px;
}

.volume-slider input[type="range"] {
  width: 100%;
}

.videoRight {
  height: 80vh;
  flex: 1;
  background-color: transparent;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .video {
    width: 100%;
  }

  .videoControl {
    width: 100%;
  }
}

/* 应用滚动条样式 */
::-webkit-scrollbar-thumb {
  background-color: var(--td-scrollbar-color);
}

::-webkit-scrollbar-thumb:horizontal:hover {
  background-color: var(--td-scrollbar-hover-color);
}

::-webkit-scrollbar-track {
  background-color: var(--td-scroll-track-color);
}
</style>
